package com.circus.trace.hanlder;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import club.zhcs.common.Result;

/**
 * 
 * @author kerbores@gmail.com
 *
 */
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

//	public static void main(String[] args) {
//		File f = Files.checkFile("/Users/kerbores/target.text");
//		for (String info : Files.readLines(Files.checkFile("/Users/kerbores/test.text"))) {
//			String appKey = "0b4b0710b41f9489";
//			String q = info.substring(4);
//			String flag = info.substring(0, 4);
//			String salt = String.valueOf(System.currentTimeMillis());
//			String sign = Lang.md5(appKey + q + salt + "bYjgXPUi36Q6is5Koh4PvO7toqNMAwTl");
//			Response response = Http.get(String.format("http://openapi.youdao.com/api?q=%s&from=zh-CHS&to=EN&appKey=%s&salt=%s&sign=%s", q, appKey, salt, sign));
//			String en = Lang.map(response.getContent()).getString("translation");
//			System.err.println(q);
//			System.err.println(flag);
//			System.err.println(en);
//			Files.appendWrite(f, String.format("%s(\"%s\",\"%s\"),\n", en, q, flag));
//		}
//	}

	Log logger = Logs.get();

	@ExceptionHandler(value = Exception.class)
	public Result defaultErrorHandler(HttpServletResponse response, Exception e) throws Exception {
		logger.error("error=>", e);
		if (e instanceof UnauthenticatedException || e instanceof AuthorizationException) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			return Result.fail("没有权限进行此操作!");
		}
		return Result.exception(e);
	}
}
